<template>
  <a-form :model="ruleForm" v-bind="layout" @finish="handleFinish">
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
        v-model:value="ruleForm.alloy_code"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in alloyCodeSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="密度" name="density">
      <a-input v-model:value="ruleForm.density" />
    </a-form-item>
    <a-form-item label="熔点" name="melting_point">
      <a-input v-model:value="ruleForm.melting_point" />
    </a-form-item>
    <a-form-item label="沸点" name="boiling_point">
      <a-input v-model:value="ruleForm.boiling_point" />
    </a-form-item>
    <a-form-item label="致密度" name="sample_density">
      <a-input v-model:value="ruleForm.sample_density" />
    </a-form-item>
    <a-form-item label="电导率" name="conductivity">
      <a-input v-model:value="ruleForm.conductivity" />
    </a-form-item>
    <a-form-item label="电阻率" name="resistivity">
      <a-input v-model:value="ruleForm.resistivity" />
    </a-form-item>
    <a-form-item label="热导率" name="thermal_conductivity">
      <a-input v-model:value="ruleForm.thermal_conductivity" />
    </a-form-item>
    <a-form-item label="热膨胀系数" name="thermal_expansion_coefficient">
      <a-input v-model:value="ruleForm.thermal_expansion_coefficient" />
    </a-form-item>
    <a-form-item label="导磁率" name="permeability">
      <a-input v-model:value="ruleForm.permeability" />
    </a-form-item>
    <a-form-item label="磁饱和强度" name="magnetic_saturation">
      <a-input v-model:value="ruleForm.magnetic_saturation" />
    </a-form-item>
    <a-form-item label="剩磁" name="remanence">
      <a-input v-model:value="ruleForm.remanence" />
    </a-form-item>
    <a-form-item label="矫顽力" name="coercive_force">
      <a-input v-model:value="ruleForm.coercive_force" />
    </a-form-item>
     <a-form-item label="液相线温度" name="liquid_temperature">
      <a-input v-model:value="ruleForm.liquid_temperature" />
    </a-form-item>
     <a-form-item label="固相线温度" name="solidus_temperature">
      <a-input v-model:value="ruleForm.solidus_temperature" />
    </a-form-item>
     <a-form-item label="熔程" name="melting_process">
      <a-input v-model:value="ruleForm.melting_process" />
    </a-form-item>
     <a-form-item label="焓" name="enthalpy">
      <a-input v-model:value="ruleForm.enthalpy" />
    </a-form-item>
     <a-form-item label="过冷度" name="supercooling_degree">
      <a-input v-model:value="ruleForm.supercooling_degree" />
    </a-form-item>
      <a-form-item label="热扩散系数" name="thermal_diffusion_coefficient">
      <a-input v-model:value="ruleForm.thermal_diffusion_coefficient" />
    </a-form-item>
     <a-form-item label="比热容" name="specific_heat_capacity">
      <a-input v-model:value="ruleForm.specific_heat_capacity" />
    </a-form-item>
     <a-form-item label="湿润力" name="wetting_force">
      <a-input v-model:value="ruleForm.wetting_force" />
    </a-form-item>
     <a-form-item label="湿润率" name="wetting_rate">
      <a-input v-model:value="ruleForm.wetting_rate" />
    </a-form-item>
     <a-form-item label="湿润时间" name="wetting_time">
      <a-input v-model:value="ruleForm.wetting_time" />
    </a-form-item>
     <a-form-item label="铺展率" name="spreading_rate">
      <a-input v-model:value="ruleForm.spreading_rate" />
    </a-form-item>
     <a-form-item label="铺展面积" name="spreading_square">
      <a-input v-model:value="ruleForm.spreading_square" />
    </a-form-item>
     <a-form-item label="湿润角" name="wetting_angle">
      <a-input v-model:value="ruleForm.wetting_angle" />
    </a-form-item>
     <a-form-item label="摩尔热容" name="molar_heat_capacity">
      <a-input v-model:value="ruleForm.molar_heat_capacity" />
    </a-form-item>

    <a-form-item label="阻抗" name="impedance">
      <a-upload
        :fileList="ruleForm.impedanceFileList"
        :beforeUpload="beforeImpedanceUpload"
        :headers="headers"
        @change="handleImpedanceChange"
      >
        <a-button> <upload-outlined /> 选择 </a-button>
      </a-upload>
    </a-form-item>
    <a-form-item label="阻抗曲线" name="impedance_curve">
        <a-upload
            :fileList="ruleForm.impedanceCurveFileList"
            :beforeUpload="beforeImpedanceCurveUpload"
            :headers="headers"
            @change="handleImpedanceCurveChange"
        >
            <a-button> <upload-outlined /> 选择 </a-button>
        </a-upload>
    </a-form-item>
    <a-form-item label="放射性" name="radioactive">
      <a-input v-model:value="ruleForm.radioactive" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script>

import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditPhysicalProperty',
    props: ['url'],
    emits: ['operate-success', 'operate-failed'],
    components:{
      UploadOutlined,
    },
  data() {
    return {
        ruleForm: {
            sample_name: '',
            alloy_code: '',
            density: '',
            melting_point: '',
            boiling_point: '',
            sample_density: '',
            conductivity: '',
            resistivity: '',
            thermal_conductivity: '',
            thermal_expansion_coefficient: '',
            permeability: '',
            magnetic_saturation: '',
            remanence: '',
            coercive_force: '',
            liquid_temperature: '',
            solidus_temperature: '',
            melting_process: '',
            enthalpy: '',
            supercooling_degree: '',
            thermal_diffusion_coefficient: '',
            specific_heat_capacity: '',
            wetting_force: '',
            wetting_rate: '',
            wetting_time: '',
            spreading_rate: '',
            spreading_square: '',
            wetting_angle: '',
            molar_heat_capacity: '',
            impedanceFileList: [],
            impedanceCurveFileList: [],
            radioactive: '',
        },
        layout: {
            labelCol: { span: 4 },
            wrapperCol: { span: 14 },
        },
        submitting: false,
        alloyCodeSelectionOptions: [],
        headers: {
            authorization: 'authorization-text',
        },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
        this.alloyCodeSelectionOptions = []
        this.axios.get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
            const data = res.data
            for(let i = 0; i < data.length; ++i){
                this.alloyCodeSelectionOptions.push({
                    url: data[i].url,
                    label: data[i].alloy_code,
                })
            }
            this.ruleForm.alloy_code = data.length === 0 ? '' :data[0].url
                  if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.alloy_code = data.alloy_code
                this.ruleForm.density = data.density
                this.ruleForm.melting_point = data.melting_point
                this.ruleForm.boiling_point = data.boiling_point
                this.ruleForm.sample_density = data.sample_density
                this.ruleForm.conductivity =
                  data.conductivity
                this.ruleForm.resistivity = data.resistivity
                  this.ruleForm.thermal_conductivity = data.thermal_conductivity
                  this.ruleForm.thermal_expansion_coefficient = data.thermal_expansion_coefficient
                  this.ruleForm.permeability = data.permeability
                  this.ruleForm.magnetic_saturation = data.magnetic_saturation
                  this.ruleForm.remanence = data.remanence
                  this.ruleForm.coercive_force = data.coercive_force
                  this.ruleForm.liquid_temperature = data.liquid_temperature
                  this.ruleForm.solidus_temperature = data.solidus_temperature
                  this.ruleForm.melting_process = data.melting_process
                  this.ruleForm.enthalpy = data.enthalpy
                  this.ruleForm.supercooling_degree = data.supercooling_degree
                  this.ruleForm.thermal_diffusion_coefficient = data.thermal_diffusion_coefficient
                  this.ruleForm.specific_heat_capacity = data.specific_heat_capacity
                  this.ruleForm.wetting_force = data.wetting_force
                  this.ruleForm.wetting_rate = data.wetting_rate
                  this.ruleForm.wetting_time = data.wetting_time
                  this.ruleForm.spreading_rate = data.spreading_rate
                  this.ruleForm.spreading_square = data.spreading_square
                  this.ruleForm.wetting_angle = data.wetting_angle
                  this.ruleForm.molar_heat_capacity = data.molar_heat_capacity
                  this.ruleForm.radioactive = data.radioactive
                  if (data.impedance_filename !== '') {
                  // console.log('not null')
                  this.ruleForm.impedanceFileList.push({
                    uid: '-1',
                    name: data.impedance_filename,
                  })
                }
                  if (data.impedance_curve_filename !== '') {
                  // console.log('not null')
                  this.ruleForm.impedanceCurveFileList.push({
                    uid: '-1',
                    name: data.impedance_curve_filename,
                  })
                }
                  this.ruleForm.radioactive = data.radioactive
              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
            console.log('Error',error.message)
            this.rule.alloy_code = ''
        })
    },
    handleFinish(values) {
        this.submitting = true
        const {
            impedanceFileList,
            impedanceCurveFileList,
        } = this.ruleForm
        const formData = new FormData()
        formData.append('sample_name', values.sample_name)
        formData.append('alloy_code', values.alloy_code)
        formData.append('density', values.density)
        formData.append('melting_point', values.melting_point)
        formData.append('boiling_point', values.boiling_point)
        formData.append('sample_density', values.sample_density)
        formData.append('conductivity', values.conductivity)
        formData.append('resistivity', values.resistivity)
        formData.append('thermal_conductivity', values.thermal_conductivity)
        formData.append('thermal_expansion_coefficient', values.thermal_expansion_coefficient)
        formData.append('permeability', values.permeability)
        formData.append('magnetic_saturation', values.magnetic_saturation)
        formData.append('remanence', values.remanence)
        formData.append('coercive_force', values.coercive_force)
        formData.append('liquid_temperature', values.liquid_temperature)
        formData.append('solidus_temperature', values.solidus_temperature)
        formData.append('melting_process', values.melting_process)
        formData.append('enthalpy', values.enthalpy)
        formData.append('supercooling_degree', values.supercooling_degree)
        formData.append('thermal_diffusion_coefficient', values.thermal_diffusion_coefficient)
        formData.append('specific_heat_capacity', values.specific_heat_capacity)
        formData.append('wetting_force', values.wetting_force)
        formData.append('wetting_rate', values.wetting_rate)
        formData.append('wetting_time', values.wetting_time)
        formData.append('spreading_rate', values.spreading_rate)
        formData.append('spreading_square', values.spreading_square)
        formData.append('wetting_angle', values.wetting_angle)
        formData.append('molar_heat_capacity', values.molar_heat_capacity)
        formData.append('radioactive', values.radioactive)
        impedanceFileList.forEach((file) => {
        // console.log(file.originFileObj)
        // console.log(file)
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file) {
          formData.append('impedance', file.originFileObj)
        }
      })
        impedanceCurveFileList.forEach((file) => {
        // console.log(file.originFileObj)
        // console.log(file)
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file) {
          formData.append('impedance_curve', file.originFileObj)
        }
      })
      if (this.url !== '') {
        // 若文件列表为空，则附加属性通知后端
        if (this.ruleForm.impedanceFileList.length === 0) {
          formData.append('impedance_empty', true)
        }
        if (this.ruleForm.impedanceCurveFileList.length === 0) {
          formData.append('impedance_curve_empty', true)
        }
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/property_management/physical_property/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
      beforeImpedanceUpload(file) {
        this.ruleForm.impedanceFileList = [
            ...this.ruleForm.impedanceFileList,
            file,
        ]
          return false
      },
      handleImpedanceChange(info) {
        let fileList = [...info.fileList]
          fileList = fileList.slice(-1)
          this.ruleForm.impedanceFileList = fileList
      },
      beforeImpedanceCurveUpload(file) {
        this.ruleForm.ImpedanceCurveFileList = [
            ...this.ruleForm.impedanceCurveFileList,
            file,
        ]
          return false
      },
      handleImpedanceCurveChange(info) {
        let fileList = [...info.fileList]
          fileList = fileList.slice(-1)
          this.ruleForm.impedanceCurveFileList = fileList
      },
  },
}
</script>

<style scoped>

</style>